<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class PostFavorite extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'post_id',
    ];

    /**
     * 获取收藏的用户
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    /**
     * 获取被收藏的文章
     */
    public function post(): BelongsTo
    {
        return $this->belongsTo(Post::class);
    }

    /**
     * 模型事件
     */
    protected static function boot()
    {
        parent::boot();

        // 创建收藏时更新文章收藏数
        static::created(function ($favorite) {
            $favorite->post->increment('favorites_count');
        });

        // 删除收藏时更新文章收藏数
        static::deleted(function ($favorite) {
            $favorite->post->decrement('favorites_count');
        });
    }
}